package com.stx.day0910;

/**
 * packageName com.stx.day0910
 *
 * @author YangYi
 * @className brainyArray
 * @date 2025/9/10
 * @description TODO
 */
public class BinarySearch {
    // 二分查找
    public static void main(String[] args){
        int[] array = {1,3,11,12,13};
        int num = 20;
        int result = binaryArrayFind(array,num);
        System.out.println("查找到的下标位置（-1为不存在数组中）："+result);
    }

    /**
     * 二分查找-前提：已经排序好了
     * @param array
     * @return
     */
    public static int binaryArrayFind(int[] array,int num){
        // 获取长度
        int minLength = 0;
        int maxLength = array.length - 1;

        while(minLength <= maxLength){
            // 计算中间长度值
            int mid = (maxLength + minLength) / 2;
            //判断中间值是否与需要的值相等
            if(num == array[mid]){
                return mid;
            }else if(num > array[mid]){
                // 去右边查找
                minLength = mid + 1;
            }else {
                // 去左边查找
                maxLength = mid - 1;
            }
        }
        return -1;
    }
}
